/**
 * @author        Nicolas Bottarini <nicolasbottarini@gmail.com>, 404 <http://www.proyecto404.com>
 * @version       $Rev: 3 $
 * @lastrevision  $Date: 2011-09-12 16:45:37 +0000 (Mon, 12 Sep 2011) $	 
 */
package com.proyecto404.core.ui.controls {
	import com.proyecto404.core.collections.IIterator;
	import com.proyecto404.core.exception.InvalidOperationException;
	
	import flash.display.FrameLabel;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	public class ReverseButton extends ButtonBase {
		
		private var _moving:Function;
		
		public function ReverseButton() {
			super();
			_moving = null;
		}
		
		protected override function onOver(e:MouseEvent):void {
			if (!enabled) {
				return;
			}
			
			if (labels.get("over").frame == overLastFrame) {
				gotoAndStop("over");
				return;
			}
			
			if (!isMoving()) {
				startMove(labels.get("over").frame, overLastFrame);
			} else {
				endMove();
				startMove(currentFrame, overLastFrame);
			}
		}
		
		protected override function onOut(e:MouseEvent):void {
			if (!enabled) {
				return;
			}

			if (labels.get("over").frame == overLastFrame) {
				gotoAndStop("active");
				return;
			}
			
			if (!isMoving()) {
				startMove(overLastFrame, labels.get("over").frame);
			} else {
				endMove();
				startMove(currentFrame, labels.get("over").frame);
			}
		}
		
		private function isMoving():Boolean {
			return _moving != null;
		}
		
		private function startMove(startFrame:int, endFrame:int):void {
			var direction:int = startFrame >= endFrame ? -1 : 1;
			if (currentFrame != startFrame) {
				gotoAndStop(startFrame);
			}
			_moving = function(e:Event):void {
				if (currentFrame == endFrame) {
					endMove();
					return;
				}
				gotoAndStop(currentFrame + direction);	
			};
			addEventListener(Event.ENTER_FRAME, _moving);
		}
		
		private function endMove():void {
			removeEventListener(Event.ENTER_FRAME, _moving);
			_moving = null;
		}
	}
}